package com.test.mytest.socket;

import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Button;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;

public class SocketClientTestApp {

	protected Shell shell;
	private Text text;
	private Text text_1;
	private Socket socket;
	private Thread thread;

	/**
	 * Launch the application.
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			SocketClientTestApp window = new SocketClientTestApp();
			window.open();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Open the window.
	 */
	public void open() {
		Display display = Display.getDefault();
		createContents();
		shell.open();
		shell.layout();
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch()) {
				display.sleep();
			}
		}
	}

	/**
	 * Create contents of the window.
	 */
	protected void createContents() {
		shell = new Shell();
		shell.setSize(306, 300);
		shell.setText("SWT Application");
		
		Button button = new Button(shell, SWT.NONE);
		button.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				sendMessage(text.getText());
			}
		});
		button.setBounds(193, 8, 80, 27);
		button.setText("发送");
		
		text = new Text(shell, SWT.BORDER);
		text.setBounds(10, 10, 177, 23);
		
		text_1 = new Text(shell, SWT.BORDER);
		text_1.setBounds(10, 51, 259, 200);

	}

	protected void sendMessage(String text2) {
		try {
			if (socket==null) {
				socket = new Socket("127.0.0.1", 12345);
			}
			OutputStream os = socket.getOutputStream();
			os.write(text2.getBytes());
			os.flush();
			System.out.println("发送消息："+text2);
			
			if (thread==null) {
				thread = new Thread(new Runnable() {
					public void run() {
						while (socket != null) {
							try {
								socket.setSoTimeout(2000);
								InputStream is = socket.getInputStream();
								byte[] b = new byte[1024];
								int read = is.read(b);
								if (read > 0) {
									System.out.println(new String(b));
								}
							} catch (Exception e) {
							}
						}
					}
				});
				thread.start();
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
